<template>
  <div class="classic-layout" :class="{ collapsed: menuCollapsed, 'dark-mode': isDarkMode }">
    <!-- 侧边栏 -->
    <aside class="sidebar" :style="{ width: sidebarWidth + 'px', [sidebarPosition]: 0 }">
      <div class="logo-container">
        <img v-if="!menuCollapsed" src="@/assets/logo.png" alt="Logo" class="logo" />
        <img v-else src="@/assets/logo-mini.png" alt="Logo" class="logo-mini" />
        <span v-if="!menuCollapsed" class="app-name">ERP系统</span>
      </div>

      <el-scrollbar class="menu-scrollbar">
        <el-menu
          :default-active="activeMenu"
          :collapse="menuCollapsed"
          :collapse-transition="false"
          :unique-opened="true"
          router
        >
          <template v-for="item in menuItems" :key="item.path">
            <!-- 一级菜单 -->
            <el-sub-menu v-if="item.children && item.children.length > 0" :index="item.path">
              <template #title>
                <el-icon><component :is="item.icon" /></el-icon>
                <span>{{ item.title }}</span>
              </template>
              <!-- 二级菜单 -->
              <template v-for="child in item.children" :key="child.path">
                <el-sub-menu v-if="child.children && child.children.length > 0" :index="child.path">
                  <template #title>{{ child.title }}</template>
                  <!-- 三级菜单 -->
                  <el-menu-item
                    v-for="subChild in child.children"
                    :key="subChild.path"
                    :index="subChild.path"
                  >
                    {{ subChild.title }}
                  </el-menu-item>
                </el-sub-menu>
                <el-menu-item v-else :index="child.path">
                  {{ child.title }}
                </el-menu-item>
              </template>
            </el-sub-menu>
            <!-- 无子菜单 -->
            <el-menu-item v-else :index="item.path">
              <el-icon><component :is="item.icon" /></el-icon>
              <template #title>{{ item.title }}</template>
            </el-menu-item>
          </template>
        </el-menu>
      </el-scrollbar>

      <!-- 折叠按钮 -->
      <div class="collapse-btn" @click="toggleSidebar">
        <el-icon>
          <component :is="menuCollapsed ? 'Expand' : 'Fold'" />
        </el-icon>
      </div>
    </aside>

    <!-- 主内容区 -->
    <div class="main-container" :style="{ marginLeft: (sidebarPosition === 'left' ? sidebarWidth : 0) + 'px', marginRight: (sidebarPosition === 'right' ? sidebarWidth : 0) + 'px' }">
      <!-- 顶部栏 -->
      <header class="header" :class="{ fixed: fixedHeader }">
        <!-- 面包屑 -->
        <el-breadcrumb v-if="showBreadcrumb" class="breadcrumb" separator="/">
          <el-breadcrumb-item v-for="(item, index) in breadcrumbs" :key="index" :to="item.path">
            {{ item.title }}
          </el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 右侧工具栏 -->
        <div class="toolbar">
          <el-tooltip content="全局搜索 (Ctrl+/)">
            <el-button circle @click="showGlobalSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="命令面板 (Ctrl+K)">
            <el-button circle @click="toggleCommandPanel">
              <el-icon><Operation /></el-icon>
            </el-button>
          </el-tooltip>
          <!-- 消息通知 -->
          <NotificationCenter />
          <el-tooltip content="全屏">
            <el-button circle @click="toggleFullscreen">
              <el-icon><FullScreen /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="导航设置">
            <el-button circle @click="showNavigationSettings">
              <el-icon><Setting /></el-icon>
            </el-button>
          </el-tooltip>
          <el-dropdown @command="handleUserCommand">
            <div class="user-avatar">
              <el-avatar :size="32" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                <el-dropdown-item command="settings">系统设置</el-dropdown-item>
                <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </header>

      <!-- 标签页 -->
      <div v-if="showTabs" class="tabs-bar">
        <el-tabs
          v-model="activeTab"
          type="card"
          closable
          @tab-remove="removeTab"
          @tab-click="handleTabClick"
        >
          <el-tab-pane
            v-for="tab in openedTabs"
            :key="tab.path"
            :label="tab.title"
            :name="tab.path"
          />
        </el-tabs>
        <div class="tabs-actions">
          <el-dropdown @command="handleTabsCommand">
            <el-button size="small" text>
              <el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="closeOther">关闭其他</el-dropdown-item>
                <el-dropdown-item command="closeAll">关闭全部</el-dropdown-item>
                <el-dropdown-item command="refresh">刷新当前</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 页面内容 -->
      <main class="content" :class="{ 'compact-mode': compactMode }">
        <router-view v-slot="{ Component }">
          <transition name="fade-transform" mode="out-in">
            <keep-alive :include="cachedViews">
              <component :is="Component" :key="$route.fullPath" />
            </keep-alive>
          </transition>
        </router-view>
      </main>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useNavigationStore } from '@/stores/navigation'
import { useUserStore } from '@/stores/user'
import { menuData } from '@/config/menu'
import NotificationCenter from '@/components/common/NotificationCenter.vue'

const route = useRoute()
const router = useRouter()
const navigationStore = useNavigationStore()

// 响应式数据
const activeMenu = computed(() => route.path)
const activeTab = ref(route.path)

// Store数据
const menuCollapsed = computed(() => navigationStore.menuCollapsed)
const sidebarWidth = computed(() => navigationStore.sidebarWidth)
const sidebarPosition = computed(() => navigationStore.settings.sidebarPosition)
const showBreadcrumb = computed(() => navigationStore.settings.showBreadcrumb)
const showTabs = computed(() => navigationStore.settings.showTabs)
const fixedHeader = computed(() => navigationStore.settings.fixedHeader)
const compactMode = computed(() => navigationStore.settings.compactMode)
const isDarkMode = computed(() => navigationStore.settings.darkMode)
const openedTabs = computed(() => navigationStore.openedTabs)

// 菜单数据
const menuItems = ref(menuData)

// 面包屑
const breadcrumbs = computed(() => {
  const matched = route.matched.filter(item => item.meta && item.meta.title)
  return matched.map(item => ({
    path: item.path,
    title: item.meta.title
  }))
})

// 缓存的视图
const cachedViews = computed(() => {
  return openedTabs.value.filter(tab => tab.keepAlive).map(tab => tab.name)
})

// 方法
const toggleSidebar = () => {
  navigationStore.toggleSidebar()
}

const showGlobalSearch = () => {
  // 触发全局搜索对话框
  window.dispatchEvent(new CustomEvent('show-global-search'))
}

const toggleCommandPanel = () => {
  navigationStore.toggleCommandPanel()
}

const toggleFullscreen = () => {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen()
  } else {
    document.exitFullscreen()
  }
}

const showNavigationSettings = () => {
  // 触发导航设置对话框
  window.dispatchEvent(new CustomEvent('show-navigation-settings'))
}

const handleUserCommand = (command) => {
  if (command === 'logout') {
    ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const userStore = useUserStore()
      userStore.logout()
      router.push('/login')
      ElMessage.success('已退出登录')
    }).catch(() => {})
  } else if (command === 'profile') {
    router.push('/system/user-settings')
  } else if (command === 'settings') {
    router.push('/system/settings')
  }
}

const removeTab = (targetPath) => {
  const tabs = openedTabs.value
  const currentIndex = tabs.findIndex(tab => tab.path === targetPath)

  if (currentIndex > -1) {
    navigationStore.removeTab(targetPath)

    if (targetPath === route.path) {
      const nextTab = tabs[currentIndex + 1] || tabs[currentIndex - 1]
      if (nextTab) {
        router.push(nextTab.path)
      } else {
        router.push('/')
      }
    }
  }
}

const handleTabClick = (tab) => {
  router.push(tab.props.name)
}

const handleTabsCommand = (command) => {
  const currentPath = route.path

  if (command === 'closeOther') {
    const currentTab = openedTabs.value.find(tab => tab.path === currentPath)
    navigationStore.clearTabs()
    if (currentTab) {
      navigationStore.addTab(currentTab)
    }
  } else if (command === 'closeAll') {
    navigationStore.clearTabs()
    router.push('/')
  } else if (command === 'refresh') {
    router.go(0)
  }
}

// 快捷键
const handleKeydown = (e) => {
  // Ctrl+K 打开命令面板
  if (e.ctrlKey && e.key === 'k') {
    e.preventDefault()
    toggleCommandPanel()
  }
  // Ctrl+/ 全局搜索
  else if (e.ctrlKey && e.key === '/') {
    e.preventDefault()
    showSearchDialog()
  }
  // Ctrl+B 切换侧边栏
  else if (e.ctrlKey && e.key === 'b') {
    e.preventDefault()
    toggleSidebar()
  }
}

// 监听路由变化，添加标签
const addCurrentTab = () => {
  if (route.meta.title) {
    navigationStore.addTab({
      path: route.path,
      title: route.meta.title,
      name: route.name,
      keepAlive: route.meta.keepAlive || false
    })
  }
}

// 生命周期
onMounted(() => {
  navigationStore.loadFromServer()
  addCurrentTab()
  document.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})

// 监听路由变化
import { watch } from 'vue'
watch(() => route.path, () => {
  addCurrentTab()
  activeTab.value = route.path
})
</script>

<style scoped>
.classic-layout {
  display: flex;
  height: 100vh;
  background: #f0f2f5;
  overflow: hidden;
}

.sidebar {
  position: fixed;
  top: 0;
  bottom: 0;
  background: #fff;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.05);
  z-index: 1000;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 20px;
  border-bottom: 1px solid #e4e7ed;
  gap: 12px;
}

.logo {
  height: 18px;
}

.logo-mini {
  height: 32px;
}

.app-name {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.menu-scrollbar {
  flex: 1;
  overflow-x: hidden;
}

.el-menu {
  border: none;
}

.collapse-btn {
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-top: 1px solid #e4e7ed;
  cursor: pointer;
  color: #606266;
  transition: all 0.3s ease;
}

.collapse-btn:hover {
  background: #f5f7fa;
  color: #409eff;
}

.main-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
  height: 100vh;
  overflow: hidden;
}

.header {
  height: 60px;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  z-index: 999;
}

.header.fixed {
  position: sticky;
  top: 0;
}

.breadcrumb {
  flex: 1;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  cursor: pointer;
}

.tabs-bar {
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.tabs-bar :deep(.el-tabs) {
  flex: 1;
}

.tabs-bar :deep(.el-tabs__header) {
  margin: 0;
  border: none;
}

.tabs-bar :deep(.el-tabs__nav) {
  border: none;
}

.tabs-actions {
  margin-left: 12px;
}

.content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  overflow-x: hidden;
  background: #f0f2f5;
  height: 0; /* 触发flex子元素的overflow */
}

.content.compact-mode {
  padding: 12px;
}

/* 过渡动画 */
.fade-transform-enter-active,
.fade-transform-leave-active {
  transition: all 0.3s ease;
}

.fade-transform-enter-from {
  opacity: 0;
  transform: translateX(-20px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

/* 暗黑模式 */
.dark-mode .sidebar {
  background: #1f1f1f;
  color: #e4e7ed;
}

.dark-mode .header {
  background: #1f1f1f;
  color: #e4e7ed;
}

.dark-mode .tabs-bar {
  background: #1f1f1f;
  border-bottom-color: #3a3a3a;
}

.dark-mode .content {
  background: #141414;
}
</style>
